<template>
  <view class="chat-page">
    <!-- 顶部导航?-->
    <view class="header-bar">
      <view class="brand">SKILLITH</view>
      <view class="user-info">
        <image :src="getAvatarUrl(userStore.profile?.avatarUrl)" class="avatar" @error="handleAvatarError" />
        <text class="nickname">{{ userStore.profile?.nickname }}</text>
      </view>
    </view>

    <!-- 聊天室内?-->
    <view class="chat-content">
      <view v-if="loading" class="loading-spinner">
        <span class="spinner"></span>
        <text>加载中...</text>
      </view>
      
      <view v-else-if="!isConnected" class="connection-status">
        <view class="status-icon">🔌</view>
        <text class="status-text">连接中...</text>
        <button class="retry-btn" @click="connectWebSocket">重试</button>
      </view>
      
      <view v-else class="chat-container">
        <!-- 快捷操作按钮 -->
        <view class="quick-actions">
          <button class="action-btn friends-btn" @click="goToFriends">
            <text class="btn-icon">👥</text>
            <text class="btn-text">我的好友</text>
          </button>
          <button class="action-btn mark-read-btn" @click="markAllAsRead">
            <text class="btn-icon">✅</text>
            <text class="btn-text">一键已读</text>
          </button>
        </view>

        <!-- 聊天记录 -->
        <view class="chat-history-section">
          <view class="section-header">
            <text class="section-title">最近聊天</text>
          </view>
          
          <view class="chat-list">
            <view 
              v-for="chat in recentChats" 
              :key="chat.other_user_id" 
              class="chat-item"
              @click="openChat(chat)"
              @touchstart="() => console.log('🔍 触摸开始:', chat.other_user_nickname)"
            >
              <image :src="getAvatarUrl(chat.other_user_avatar)" class="chat-avatar" @error="handleChatAvatarError" />
              <view class="chat-info">
                <text class="chat-name">{{ chat.other_user_nickname }}</text>
                <text class="last-message">{{ chat.last_message }}</text>
              </view>
              <view class="chat-meta">
                <text class="last-time">{{ formatTime(chat.last_message_time) }}</text>
                <view v-if="chat.unread_count > 0" class="unread-badge">
                  {{ chat.unread_count }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { NETWORK_CONFIG } from '@/config/network.js'
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/user'
import { getAvatarUrl } from '@/utils/imageUtils.js'

const userStore = useUserStore()

// 数据
const loading = ref(false)
const isConnected = ref(false)
const friends = ref([])
const recentChats = ref([])
const shouldReconnect = ref(true) // 是否应该重连
// 本地乐观已读集合（持久化到Storage，跨会话/重登录生效）
const loadLocalRead = () => {
  try {
    const raw = uni.getStorageSync('locallyReadSet')
    if (raw) {
      const arr = JSON.parse(raw)
      return new Set((arr || []).map(n => Number(n)))
    }
  } catch (e) { console.warn('读取本地已读集合失败', e) }
  return new Set()
}
const locallyReadSet = ref(loadLocalRead())

// WebSocket连接
let ws = null

// 初始?
onMounted(() => {
  initChat()
})

onShow(async () => {
  if (isConnected.value) {
    await loadFriends()
    await loadRecentChats()
    // 注意：不在这里调用 applyLocalReadMask()，因为这会覆盖真实的未读数量
    // 真实的未读数量应该从数据库获取
  }
})

// 监听全局WebSocket消息
onMounted(() => {
  uni.$on('chatMessage', handleChatMessage)
  uni.$on('newMessage', (message) => {
    console.log('收到新消息事件（来自聊天详情页面?', message)
    updateRecentChats(message)
  })
  uni.$on('chat-marked-read', (data) => {
    console.log('收到聊天已读事件:', data)
    // 更新本地聊天列表的未读数
    const chat = recentChats.value.find(c => c.other_user_id === data.otherUserId)
    if (chat) {
      chat.unread_count = 0
      console.log('已更新聊天未读数量为0')
    }
    // 写入本地已读集，防止返回后因后端延迟又出现红点
    markLocalRead(data.otherUserId)
  })
  uni.$on('chat-consumed-unread', (data) => {
    // 聊天详情滚动到底部后，消费了未读，新消息按钮清零时同步清除列表红点
    const chat = recentChats.value.find(c => c.other_user_id === Number(data.otherUserId))
    if (chat) chat.unread_count = 0
    markLocalRead(data.otherUserId)
  })
})

onUnmounted(() => {
  uni.$off('chatMessage', handleChatMessage)
  uni.$off('newMessage')
  uni.$off('chat-marked-read')
})

// 初始化聊天功能
const initChat = async () => {
  loading.value = true
  try {
    await connectWebSocket()
    await loadFriends()
    await loadRecentChats()
  } catch (error) {
    console.error('初始化聊天功能失败', error)
    uni.showToast({
      title: '初始化失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 连接WebSocket（使用全局连接）
const connectWebSocket = () => {
  return new Promise((resolve, reject) => {
    console.log('使用全局WebSocket连接，无需创建新连接')
    isConnected.value = true
    resolve()
  })
}

// 处理聊天消息
const handleChatMessage = (data) => {
  console.log('收到聊天消息:', data)
  
  if (data.message) {
    const message = data.message
    console.log('处理新消息', message)
    
    // 检查是否是发给当前用户的消息（需要显示未读红点）
    const currentUserId = userStore.profile?.uid
    const isToCurrentUser = Number(message.receiverId) === Number(currentUserId)
    
    console.log('🔍 消息处理调试:')
    console.log('🔍 当前用户ID:', currentUserId, '类型:', typeof currentUserId)
    console.log('🔍 消息接收者ID:', message.receiverId, '类型:', typeof message.receiverId)
    console.log('🔍 是否发给当前用户:', isToCurrentUser)
    
    if (isToCurrentUser) {
      // 找到对应的聊天项并更新消息内容
      const chat = recentChats.value.find(c => c.other_user_id === Number(message.senderId))
      if (chat) {
        // 更新最后消息内容
        chat.last_message = message.content
        chat.last_message_time = message.createdAt || message.createTime
        
        // 将更新的聊天项移到列表顶部
        const updatedChat = recentChats.value.splice(recentChats.value.indexOf(chat), 1)[0]
        recentChats.value.unshift(updatedChat)
        
        console.log('🔍 聊天列表已更新，准备获取真实未读数量')
        
        // 获取真实的未读数量（从数据库统计）
        loadRealUnreadCounts()
      } else {
        console.log('🔍 未找到对应的聊天项，用户ID:', message.senderId)
        // 如果没找到现有聊天，重新加载数据
        updateRecentChats(message)
      }
    } else {
      console.log('🔍 不是发给当前用户的消息，跳过未读计数')
      // 不是发给当前用户的消息，只更新聊天列表
      updateRecentChats(message)
    }
  }
}

// 加载好友列表
const loadFriends = async () => {
  try {
    const token = uni.getStorageSync('accessToken')
    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/friends`,
      method: 'GET',
      header: { 'Access-Token': `Bearer ${token}` }
    })
    
    if (response.data && response.data.success) {
      friends.value = response.data.data || []
    }
  } catch (error) {
    console.error('加载好友列表失败:', error)
  }
}

// 加载最近聊天
const loadRecentChats = async () => {
  try {
    const token = uni.getStorageSync('accessToken')
    console.log('加载最近聊天记录')
    
    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/simple-chat/recent`,
      method: 'GET',
      header: { 'Access-Token': `Bearer ${token}` }
    })
    
    console.log('最近聊天响应', response.data)
    
    if (response.data && response.data.code === 200) {
      const serverData = response.data.data || []
      
      // 更新聊天列表数据
      recentChats.value = serverData
      
      // 获取真实的未读数量（从数据库 is_read = 0 统计）
      await loadRealUnreadCounts()
      
      // 注意：不在这里调用 applyLocalReadMask()，因为这会覆盖真实的未读数量
      // applyLocalReadMask() 只在用户真正进入聊天详情页时调用
      console.log('最近聊天记录', recentChats.value)
    } else {
      console.error('获取最近聊天失败', response.data)
    }
  } catch (error) {
    console.error('加载最近聊天失败', error)
  }
}

// 获取真实的未读数量（从数据库统计 is_read = 0）
const loadRealUnreadCounts = async () => {
  try {
    const token = uni.getStorageSync('accessToken')
    console.log('🔍 获取真实未读数量...')
    
    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/simple-chat/real-unread-counts`,
      method: 'GET',
      header: { 'Access-Token': `Bearer ${token}` }
    })
    
    console.log('🔍 真实未读数量响应:', response.data)
    
    if (response.data && response.data.code === 200) {
      const unreadCounts = response.data.data || {}
      
      // 计算总未读数量
      let totalUnread = 0
      
      // 更新每个聊天的真实未读数量
      recentChats.value.forEach(chat => {
        const realUnreadCount = unreadCounts[chat.other_user_id] || 0
        chat.unread_count = realUnreadCount
        totalUnread += realUnreadCount
        console.log(`🔍 用户${chat.other_user_id}真实未读数量: ${realUnreadCount}`)
      })
      
      // 更新底部导航栏的红点
      if (totalUnread > 0) {
        uni.setTabBarBadge({
          index: 1, // 聊天室在第2个位置（索引为1）
          text: totalUnread > 99 ? '99+' : totalUnread.toString()
        })
        console.log('🔍 设置聊天室tabBar红点:', totalUnread)
      } else {
        uni.removeTabBarBadge({
          index: 1
        })
        console.log('🔍 移除聊天室tabBar红点')
      }
      
      console.log('🔍 已更新所有聊天的真实未读数量，总未读数:', totalUnread)
    } else {
      console.error('获取真实未读数量失败:', response.data)
    }
  } catch (error) {
    console.error('获取真实未读数量失败:', error)
  }
}

// 开始聊天
const startChat = (friend) => {
  uni.navigateTo({
    url: `/pages/social/chat-detail?userId=${friend.id}&name=${friend.nickname}`
  })
}

// 打开聊天
const openChat = async (chat) => {
  console.log('🔍 点击聊天项:', chat)
  
  // 本地立即清零，确保红点立刻消失；并广播事件给其它页面
  chat.unread_count = 0
  
  // 记录到本地已读集合，避免页面切换时红点重新出现
  markLocalRead(chat.other_user_id)
  
  uni.$emit('chat-marked-read', { otherUserId: chat.other_user_id })

  // 后台标记已读（失败也不阻塞跳转）
  ;(async () => {
    try {
      const token = uni.getStorageSync('accessToken')
      const response = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/simple-chat/mark-read`,
        method: 'POST',
        data: { otherUserId: chat.other_user_id },
        header: { 'Access-Token': `Bearer ${token}` }
      })
      console.log('📖 标记已读API响应:', response.data)
    } catch (e) {
      console.error('标记已读后台请求失败（已乐观更新）:', e)
    }
  })()

  // 跳转到聊天详情
  const chatUrl = `/pages/social/chat-detail?userId=${chat.other_user_id}&name=${encodeURIComponent(chat.other_user_nickname)}`
  console.log('🔍 准备跳转到:', chatUrl)
  
  // 使用 setTimeout 避免导航锁定问题
  setTimeout(() => {
    uni.navigateTo({
      url: chatUrl,
      success: () => {
        console.log('✅ 聊天详情页面跳转成功')
      },
      fail: (err) => {
        console.error('❌ 聊天详情页面跳转失败:', err)
        // 如果 navigateTo 失败，尝试使用 reLaunch
        console.log('🔄 尝试使用 reLaunch 跳转')
        uni.reLaunch({
          url: chatUrl,
          success: () => {
            console.log('✅ reLaunch 跳转成功')
          },
          fail: (err2) => {
            console.error('❌ reLaunch 也失败了:', err2)
          }
        })
      }
    })
  }, 100)
}

// 跳转到好友页
const goToFriends = () => {
  uni.navigateTo({
    url: '/pages/social/friends/index'
  })
}


// 一键已读
const markAllAsRead = async () => {
  try {
    const token = uni.getStorageSync('accessToken')
    
    // 调用后端批量标记已读API
    await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/simple-chat/mark-all-read`,
      method: 'POST',
      data: {},
      header: { 'Access-Token': `Bearer ${token}` }
    })
    
    // 重新加载最近聊天以获取最新的未读数量
    await loadRecentChats()
    
    uni.showToast({
      title: '已标记全部已读',
      icon: 'success'
    })
  } catch (error) {
    console.error('标记已读失败:', error)
    uni.showToast({
      title: '标记已读失败',
      icon: 'none'
    })
  }
}

// 更新最近聊天
const updateRecentChats = async (message) => {
  console.log('收到新消息，重新加载最近聊天', message)
  
  // 重新从后端获取最新的聊天列表和未读数量
  await loadRecentChats()
  
  // 注意：不在这里调用 applyLocalReadMask()，因为这会覆盖真实的未读数量
  // 真实的未读数量应该从数据库获取，而不是被本地已读状态覆盖
}

// 记录本地乐观已读
const markLocalRead = (otherUserId) => {
  try {
    const set = locallyReadSet.value
    set.add(Number(otherUserId))
    locallyReadSet.value = new Set(set)
    uni.setStorageSync('locallyReadSet', JSON.stringify(Array.from(set)))
  } catch (e) {
    console.warn('记录本地已读失败', e)
  }
}

// 应用本地乐观已读覆盖到最近聊天列表
const applyLocalReadMask = () => {
  try {
    if (!recentChats.value || recentChats.value.length === 0) return
    const set = locallyReadSet.value
    if (!set || set.size === 0) return
    recentChats.value.forEach(chat => {
      if (set.has(Number(chat.other_user_id))) {
        chat.unread_count = 0
      }
    })
  } catch (e) {
    console.warn('应用本地已读覆盖失败', e)
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  return date.toLocaleDateString()
}

// 头像错误处理
const handleAvatarError = () => {
  console.log('用户头像加载失败')
}

const handleFriendAvatarError = () => {
  console.log('好友头像加载失败')
}

const handleChatAvatarError = () => {
  console.log('聊天头像加载失败')
}

// 组件卸载时关闭WebSocket
onUnmounted(() => {
  if (ws) {
    // 微信小程序中关闭WebSocket连接
    ws.close({
      code: 1000,
      reason: '页面关闭'
    })
  }
})
</script>

<style scoped>
.chat-page {
  background: #f5f5f5;
  min-height: 100vh;
}

.header-bar {
  background: #4A90E2;
  color: white;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.brand {
  font-size: 20px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.nickname {
  font-size: 14px;
  color: white;
}

.chat-content {
  padding: 16px;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  gap: 16px;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #4A90E2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.connection-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  gap: 16px;
}

.status-icon {
  font-size: 48px;
}

.status-text {
  color: #666;
  font-size: 16px;
}

.retry-btn {
  background: #4A90E2;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
}

.chat-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.quick-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
  width: 100%;
}

.action-btn, .action-btn.navigator, navigator.action-btn {
  flex: 1;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 0 18px;
  border: none;
  border-radius: 12px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
  cursor: pointer;
  transition: all 0.3s ease;
  height: 44px;
  min-height: 44px;
  line-height: 1;
  text-decoration: none;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 强化选择器，确保在 navigator 上生效 */
.action-btn.friends-btn, navigator.action-btn.friends-btn {
  background: linear-gradient(135deg, #4A90E2, #357ABD);
  color: #fff;
}

.action-btn.mark-read-btn, navigator.action-btn.mark-read-btn {
  background: linear-gradient(135deg, #4CAF50, #45A049);
  color: #fff;
}


/* 图标与文字颜色在深色底上保持可读 */
.friends-btn .btn-icon, .friends-btn .btn-text,
.mark-read-btn .btn-icon, .mark-read-btn .btn-text {
  color: #fff;
}

/* 悬浮与按压反馈 */
.action-btn:hover, navigator.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.16);
}

.action-btn:active, navigator.action-btn:active {
  transform: translateY(-1px) scale(0.99);
}

.btn-icon {
  font-size: 18px;
  flex-shrink: 0;
}

.btn-text {
  font-size: 14px;
  font-weight: 600;
  white-space: nowrap;
}

.friends-section,
.chat-history-section {
  background: white;
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.add-friend-btn {
  background: #4A90E2;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
}

.friends-list,
.chat-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.friend-item,
.chat-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.friend-item:hover,
.chat-item:hover {
  background: #f8f9fa;
}

.friend-avatar,
.chat-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
}

.friend-info,
.chat-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.friend-name,
.chat-name {
  font-weight: 600;
  color: #333;
  font-size: 13px;
}

.friend-status {
  font-size: 12px;
  color: #666;
}

.friend-status.online {
  color: #4CAF50;
}

.last-message {
  font-size: 11px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.last-time {
  font-size: 11px;
  color: #999;
}

.unread-badge {
  background: #ff4757;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 10px;
  font-weight: 600;
  min-width: 16px;
  text-align: center;
}
</style>
